package com.pafcio.dde.client;

import java.util.ArrayList;
import java.util.List;

import com.neva.DdeClient;
import com.neva.DdeUtil;
import com.pafcio.dde.shared.ConversationDetails;

import edu.emory.mathcs.backport.java.util.Collections;

public class SimpleDDEClient extends DdeClient {

	private String topic;
	private List<ConversationDetails> conversations = new ArrayList<ConversationDetails>();

	private void setConversationDetails(ConversationDetails conversationDetails) {
		conversations.add(conversationDetails);
	}

	protected List<ConversationDetails> getConversationDetails() {
		return conversations;
	}

	public void start() {
		tryConnect();
		tryStartAdvising(getConversationDetails());
	}

	public void stop() {
		tryStopAdvising(getConversationDetails());
	}
	
	public void addConversationDetails(ConversationDetails details){
		conversations.add(details);
		tryStartAdvising(Collections.singletonList(details));
	}
	
	public void removeConversationDetails(ConversationDetails details){
		conversations.remove(details);
		tryStopAdvising(Collections.singletonList(details));
	}

	private void tryStopAdvising(List<ConversationDetails> list) {
		try {
			stopAdvising(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void stopAdvising(List<ConversationDetails> list) throws Exception{
		for (ConversationDetails conversationDetails : list) {
			for (String item : conversationDetails.getItems()) {
				stopAdvise(item, DdeUtil.CF_TEXT, -1);			
			}
		}
	}

	private void tryStartAdvising(List<ConversationDetails> list) {
		try {
			startAdvising(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startAdvising(List<ConversationDetails> list) throws Exception {
		for (ConversationDetails conversationDetails : list) {
			for (String item : conversationDetails.getItems()) {
				startAdvise(item, DdeUtil.CF_TEXT, -1);
			}			
		}
	}

	private void tryConnect() {
		try {
			connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void connect() throws Exception {
		connect(service, topic);
	}

	public SimpleDDEClient withService(String service) {
		this.service = service;
		return this;
	}

	public SimpleDDEClient withConversationDetails(ConversationDetails conversationDetails) {
		this.setConversationDetails(conversationDetails);
		return this;
	}

	public SimpleDDEClient withTopic(String topic) {
		this.topic = topic;
		return this;
	}
}